package com.typingtutor.ui;

import lombok.extern.slf4j.Slf4j;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class KanaCanvas extends JPanel {
    @lombok.Setter
    private List<String> textList;
    private Font baseFont;
    private static final int MIN_FONT_SIZE = 12;
    private static final int HORIZONTAL_PADDING = 20; // 左右边距

    public KanaCanvas(Font font) {
        this.baseFont = font;
        setPreferredSize(new Dimension(400, 300));
        this.textList = new ArrayList<>();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (textList == null || textList.isEmpty()) return;

        // 获取实际绘制区域尺寸
        Insets insets = getInsets();
        int availableWidth = getWidth() - insets.left - insets.right - HORIZONTAL_PADDING * 2;
        int availableHeight = getHeight() - insets.top - insets.bottom;

        // 动态计算字体大小
        int fontSize = calculateOptimalFontSize(g, availableWidth, availableHeight);
        Font font = baseFont.deriveFont((float) fontSize);
        g.setFont(font);
        FontMetrics fm = g.getFontMetrics();

        // 垂直居中布局
        int totalTextHeight = fm.getHeight() * textList.size();
        int startY = (getHeight() - totalTextHeight) / 2 + fm.getAscent();

        // 绘制所有文本
        for (String text : textList) {
            int textWidth = fm.stringWidth(text);
            int x = (getWidth() - textWidth) / 2;
            g.drawString(text, x, startY);
            startY += fm.getHeight();
        }
    }

    private int calculateOptimalFontSize(Graphics g, int maxWidth, int maxHeight) {
        int minFontSize = MIN_FONT_SIZE;
        int maxFontSize = 72;
        int optimalSize = maxFontSize;

        // 二分查找最佳字体大小
        while (minFontSize <= maxFontSize) {
            int midSize = (minFontSize + maxFontSize) / 2;
            Font testFont = baseFont.deriveFont((float) midSize);
            FontMetrics fm = g.getFontMetrics(testFont);

            // 检查垂直空间
            int requiredHeight = fm.getHeight() * textList.size();
            boolean verticalFit = requiredHeight <= maxHeight;

            // 检查水平空间
            boolean horizontalFit = true;
            for (String text : textList) {
                if (fm.stringWidth(text) > maxWidth) {
                    horizontalFit = false;
                    break;
                }
            }

            if (verticalFit && horizontalFit) {
                optimalSize = midSize;
                minFontSize = midSize + 1;
            } else {
                maxFontSize = midSize - 1;
            }
        }
        return optimalSize;
    }
}